<template>
    <div>
        <a-table :dataSource="taskList"
                 :columns="columns"
                 :pagination="false"
                 style="margin-top: 10px"
                 bordered>
            <template #createTime="{text,record}">
                {{this.$moment(text).format('YYYY-MM-DD HH:mm:ss')}}
            </template>
            <template v-slot:action="{text,record}">
                <a-space>
                    <a-button type="primary" @click="showDrawer(record)">办理任务</a-button>
                    <a-popconfirm
                            title="删除数据无法恢复，请确认是否删除？"
                            ok-text="是"
                            cancel-text="否"
                            @confirm="okDelete(record.id)"
                    >
                        <a-button type="danger">删除</a-button>
                    </a-popconfirm>
                </a-space>
            </template>
        </a-table>
        <a-drawer
                title="资质审核详情"
                :width="1000"
                :visible="visible"
                :body-style="{ paddingBottom: '40px' }"
                :footer-style="{ textAlign: 'right' }"
                @close="onClose"
        >
            <a-form :model="drawerData.qualificationInfo" layout="vertical">
                <a-row :gutter="16">
                    <a-col :span="12">
                        <a-form-item label="申请机构" name="officeName">
                            <a-select
                                    ref="select"
                                    :disabled="disabledFlag"
                                    v-model:value="drawerData.qualificationInfo.officeId"
                                    style="width: 100%"
                                    :options="officeList"
                                    :field-names="{label:'name',value:'id'}"
                            ></a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :span="6">
                        <a-form-item label="申请人" name="uploadUserName">
                            <a-input v-model:value="drawerData.qualificationInfo.uploadUserName" :disabled="true"/>
                        </a-form-item>
                    </a-col>
                    <a-col :span="6">
                        <a-form-item label="资质类型" name="type">
                            <a-tag v-if="drawerData.qualificationInfo.type == 1" color="success">
                                产废方
                            </a-tag>
                            <a-tag v-if="drawerData.qualificationInfo.type == 2" color="success">
                                运输方
                            </a-tag>
                            <a-tag v-if="drawerData.qualificationInfo.type == 3" color="success">
                                处置方
                            </a-tag>
                        </a-form-item>
                    </a-col>
                </a-row>
                <a-row :gutter="16">
                    <a-col :span="12">
                        <a-form-item label="资质审核员" name="checkUserName">
                            <a-select
                                    ref="select"
                                    :disabled="true"
                                    v-model:value="drawerData.qualificationInfo.checkUserId"
                                    placeholder="暂无"
                                    style="width: 100%"
                                    :options="userList"
                                    :field-names="{label:'name',value:'id'}"
                            ></a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item label="审核状态" name="status">
                            <a-tag v-if="drawerData.qualificationInfo.uploadUserId == loginUser.id
                            && drawerData.comments.length != 0" color="warning">
                                <template #icon>
                                    <exclamation-circle-outlined/>
                                </template>
                                申请不通过
                            </a-tag>
                            <a-tag v-else color="processing">
                                <template #icon>
                                    <sync-outlined :spin="true"/>
                                </template>
                                审批中
                            </a-tag>
                        </a-form-item>
                    </a-col>
                </a-row>
                <a-row :gutter="16">
                    <a-col :span="24">
                        <a-form-item label="资质证书" name="address">
                            <a-upload
                                    v-model:file-list="fileList"
                                    :disabled="disabledFlag"
                                    name="file"
                                    list-type="picture-card"
                                    class="avatar-uploader"
                                    :show-upload-list="false"
                                    action="http://localhost:8086/upload/uploadAvatar"
                                    :before-upload="beforeUpload"
                                    @change="handleChange"
                            >
                                <img v-if="imageUrl" :src="imageUrl" alt="avatar"
                                         style="width: 100px;height: 100px;"/>
                                <div v-else>
                                    <loading-outlined v-if="loading"></loading-outlined>
                                    <plus-outlined v-else></plus-outlined>
                                    <div class="ant-upload-text">Upload</div>
                                </div>
                            </a-upload>
                        </a-form-item>
                    </a-col>
                </a-row>
                <a-row :gutter="16">
                    <a-col :span="24">
                        <a-form-item label="申请详情" name="description">
                            <a-textarea v-model:value="drawerData.qualificationInfo.description"
                                        :disabled="disabledFlag" :rows="3"/>
                        </a-form-item>
                    </a-col>
                </a-row>
                <a-row :gutter="16">
                    <a-col :span="24">
                        <a-form-item label="批注"
                                     v-bind="validateInfos.comment"
                                     name="comment">
                            <a-textarea v-model:value="drawerData.comment" :rows="3"/>
                        </a-form-item>
                    </a-col>
                </a-row>
                <a-row :gutter="16">
                    <a-col :span="24">
                        <a-space>
                            <a-button v-for="(item,index) in drawerData.buttonList"
                                      :key="index" type="primary"
                                      @click="submitOk(item)">
                                {{item}}
                            </a-button>
                        </a-space>
                    </a-col>
                </a-row>
            </a-form>
            <a-table :dataSource="drawerData.comments"
                     :columns="commentColumns"
                     :pagination="false"
                     bordered>
                <template #user="{text,record}">
                    {{beLongUser(text)}}
                </template>
                <template #time="{text,record}">
                    {{this.$moment(text).format('YYYY-MM-DD HH:mm:ss')}}
                </template>
            </a-table>
        </a-drawer>
    </div>
</template>

<script>
    import {ref, onMounted} from 'vue'
    import axios from 'axios'
    import {message, Form} from 'ant-design-vue'
    import {SyncOutlined, ExclamationCircleOutlined} from '@ant-design/icons-vue'
    import cookies from 'js-cookie'
    export default {
        name: "qualificationAudit",
        components: {
            SyncOutlined,
            ExclamationCircleOutlined
        },
        setup() {
            const columns = [
                {
                    title: '任务ID',
                    dataIndex: 'id',
                    key: 'id',
                    align: 'center'
                },
                {
                    title: '任务名称',
                    dataIndex: 'name',
                    key: 'name',
                    align: 'center'
                },
                {
                    title: '申请时间',
                    dataIndex: 'createTime',
                    key: 'createTime',
                    slots: {customRender: 'createTime'},
                    align: 'center'
                },
                {
                    title: '操作',
                    key: 'action',
                    slots: {customRender: 'action'},
                    align: 'center'
                }
            ]
            const commentColumns = [
                {
                    title: '时间',
                    dataIndex: 'time',
                    key: 'time',
                    slots: {customRender: 'time'}
                },
                {
                    title: '批注人',
                    dataIndex: 'userId',
                    key: 'userId',
                    slots: {customRender: 'user'}
                },
                {
                    title: '批注信息',
                    dataIndex: 'fullMessage',
                    key: 'fullMessage',
                },
            ]

            const useForm = Form.useForm
            const loginUser = ref({})
            const task = ref({})
            const taskList = ref()
            const officeList = ref([])
            const userList = ref([])
            const drawerData = ref({
                comment: ''
            })
            const {validate, validateInfos} = useForm(drawerData, {
                comment: [{required: true, message: '请输入批注信息', trigger: ['submit', 'change']}]
            })
            const visible = ref(false)
            const disabledFlag = ref(true)

            const fileList = ref([]);
            const loading = ref(false);
            const imageUrl = ref('');

            const handleChange = info => {
                if (info.file.status === 'uploading') {
                    console.log("上传uploading信息：", info)
                    loading.value = true;
                    return;
                }
                if (info.file.status === 'done') {
                    console.log("上传done信息：", info)
                    imageUrl.value = info.file.response
                    drawerData.value.qualificationInfo.address = imageUrl.value
                    loading.value = false
                }
                if (info.file.status === 'error') {
                    console.log("上传error信息：", info)
                    loading.value = false;
                    message.error('upload error');
                }
            };

            const beforeUpload = file => {
                const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
                if (!isJpgOrPng) {
                    message.error('You can only upload JPG file!');
                }
                const isLt5M = file.size / 1024 / 1024 < 5;
                if (!isLt5M) {
                    message.error('Image must smaller than 5MB!');
                }
                return isJpgOrPng && isLt5M;
            };

            const load = () => {
                axios.get('qualificationProcess/queryQualificationTaskByUserId/' + loginUser.value.id)
                    .then(rs => {
                    console.log("查找待办事务结果：", rs)
                    taskList.value = rs.data.data
                })
            }

            const okDelete = (id) => {
                console.log("要删除的ID：" + id)
                axios.delete('/task/delete/' + id).then(rs => {
                    if (rs.data.code == 200) {
                        message.success("删除成功")
                        load()
                    } else {
                        message.error(rs.data.message)
                    }
                })
            }

            const showDrawer = obj => {
                task.value = JSON.parse(JSON.stringify(obj))
                axios.get('/qualificationProcess/viewTaskForm/' + obj.id).then(rs => {
                    console.log("获取task信息结果：", rs)
                    drawerData.value = rs.data.data
                    drawerData.value.comment = ''
                    imageUrl.value = drawerData.value.qualificationInfo.address
                    if (drawerData.value.qualificationInfo.checkUserName == undefined) {
                        drawerData.value.qualificationInfo.checkUserName = '暂无'
                    }
                    if (drawerData.value.qualificationInfo.uploadUserId == loginUser.value.id){
                        disabledFlag.value = false;
                    }

                    visible.value = true
                })
            }
            const onClose = () => {
                console.log("关闭")
                visible.value = false
            }
            const submitOk = (buttonValue) => {
                // message.success("提交")
                validate().then(() => {
                    axios.post('/qualificationProcess/complete', {
                        qualification: drawerData.value.qualificationInfo,
                        buttonValue: buttonValue,
                        userId: loginUser.value.id,
                        taskId: task.value.id,
                        comment: drawerData.value.comment
                    }).then(rs => {
                        if (rs.data.code == 200) {
                            message.success("审批成功")
                            visible.value = false
                            load()
                        }
                    })
                }).catch(() => {
                    console.log("校验不通过")
                })
            }

            const beLongUser = (userId) => {
                let rs = ''
                userList.value.forEach(val => {
                    if (val.id == userId) {
                        rs = val.name
                        return rs
                    }
                })
                return rs == '' ? userId : rs
            }

            onMounted(() => {
                loginUser.value = JSON.parse(cookies.get("user"))
                axios.get('sys-user/queryAll').then(rs=>{
                    userList.value = rs.data.data
                })
                axios.get('sys-office/queryAll').then(rs=>{
                    officeList.value = rs.data.data
                })
                load()
            })
            return {
                columns,
                load,
                okDelete,
                task,
                taskList,
                showDrawer,
                visible,
                onClose,
                submitOk,
                drawerData,
                commentColumns,
                validateInfos,
                loginUser,
                imageUrl,
                loading,
                fileList,
                handleChange,
                beforeUpload,
                disabledFlag,
                officeList,
                userList,
                beLongUser
            }
        }
    }
</script>

<style scoped>

</style>